//
//  GestureLockViewController.m
//  HuaMuJinRong
//
//  Created by Cindy on 15/12/25.
//  Copyright (c) 2015年 EIMS. All rights reserved.
//

#import "OpenGestureLockViewController.h"
#import "NSString+UserInfo.h"
#import "NSString+Date.h"
#import "GestureLockView.h"
#import "TabViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "GesDatabase.h"
#import "UIImageView+WebCache.h"
#import "SetGestureLockViewController.h"
#import "AppDelegate.h"
#import "CommonClass.H"
#import "FingerDataBase.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "SGLoginViewController.h"

@interface OpenGestureLockViewController ()<GestureLockViewDelegate, HTTPClientDelegate,UIAlertViewDelegate>
{
    NSInteger _count;// 手势计数器
    CGFloat _lockViewTop;
    CGFloat _space;
}

@property (nonatomic, strong) UIView *gestureBackView;
@property (nonatomic, strong) GestureLockView *lockView;
@property (nonatomic, strong) UIImageView *headView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *againLabel;
@property (nonatomic, strong) UIButton *otherBtn;
@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, strong) UIButton *backBtn;
@end

@implementation OpenGestureLockViewController
#pragma mark - Life Cycle
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
     self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    
    [self initData];
    
    [self initView];
    
    if (self.type == 2) {
       [self ShowBackBtn];
    }
    
}

/**
 * 初始化返回按钮
 */
- (void)ShowBackBtn
{
   
    [self.view addSubview:self.backBtn];
    
    
    
}
- (UIButton *)backBtn{
    if (_backBtn == nil) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(15, 25, 20, 20);
        [_backBtn setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}
- (void)clickBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)checkFingerStaus {
    //是否开启手势密码
    NSString *account=[[AppDefaultUtil sharedInstance] getDefaultAccount];
    NSString *fingerState=[[FingerDataBase getInstance] getFingerState:account];
    if ([fingerState isEqualToString:@"1"]) {
        [self evaluatePolicy];
    }
}

/**
 *  验证指纹密码
 */
- (void)evaluatePolicy {
    LAContext *context = [[LAContext alloc] init];
    // show the authentication UI with our reason string
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(@"通过Home键验证已有手机指纹", nil) reply:
     ^(BOOL success, NSError *authenticationError) {
         if(success) {
             [self openLockSucceed];
         }else {
         }
     }];
}

-(void) initData{
    
    _count = 0;
    
    _space = MSHIGHT <= 568?0:15;
    
    _lockViewTop = MSHIGHT <= 480?(self.view.frame.size.height*0.5+35):(self.view.frame.size.height*0.5+60+_space);
}

- (void)initView
{
 
    _gestureBackView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT) backgroundColor:SETCOLOR(24, 50, 68, 1.0) superview:self.view];
    
    //self.view.backgroundColor = SETCOLOR(144, 122, 111, 1.0);
    
    _headView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width*0.5-37.5, 60+_space, 75, 75)];
    _headView.layer.cornerRadius = 37.5;
    _headView.userInteractionEnabled = NO;
    _headView.layer.masksToBounds = YES;
    [_gestureBackView addSubview:_headView];
    
    // 加载上次登陆的头像或者默认的头像
    NSString *imageUrl = [[AppDefaultUtil sharedInstance] getDefaultHeaderImageUrl];
    DLOG(@"imageUrl====%@=", imageUrl);
    
    [_headView sd_setImageWithURL:[NSURL URLWithString:imageUrl]
                  placeholderImage:KDefaultHead];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_headView.frame)+5, MSWIDTH-20, 30)];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.tag = 110;
    _nameLabel.font = [UIFont systemFontOfSize:15.0f];
    _nameLabel.textColor = [UIColor whiteColor];
    NSString *userName = [[AppDefaultUtil sharedInstance]getDefaultAccount];
    if (userName.length > 10) {
        userName = [NSString phoneNumToAsterisk:userName];
    }
    _nameLabel.text = userName;
    [_gestureBackView addSubview:_nameLabel];
    
    _againLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, MSHIGHT-_lockViewTop-40, self.view.frame.size.width, 30)];
    _againLabel.font = [UIFont systemFontOfSize:14.0f];
    _againLabel.tag = 100;
    _againLabel.textAlignment = NSTextAlignmentCenter;
    _againLabel.textColor = [UIColor whiteColor];
    if (self.type == ModifyGesturePwd || self.type == CloseGesturePwd) {
        _againLabel.text = @"请输入原始密码";
        [self ShowBackBtn];
        
    }else {
        _againLabel.text = @"请绘制手势密码";
    }
    [_gestureBackView addSubview:_againLabel];
    
    if (self.type==ModifyGesturePwd || self.type==CloseGesturePwd) {
        UIButton *forgetpwd = [UIButton buttonWithType:UIButtonTypeCustom];
        forgetpwd.frame = CGRectMake(15, self.view.frame.size.height-40, 100, 15);
        forgetpwd.titleLabel.font = [UIFont systemFontOfSize:13.0];
        [forgetpwd setTitle:@"忘记手势密码?" forState:UIControlStateNormal];
        [forgetpwd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [forgetpwd addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_gestureBackView addSubview:forgetpwd];
    }else {
        UIButton *forgetpwd = [UIButton buttonWithType:UIButtonTypeCustom];
        forgetpwd.frame = CGRectMake(15, self.view.frame.size.height-40, 100, 15);
        forgetpwd.titleLabel.font = [UIFont systemFontOfSize:13.0];
        [forgetpwd setTitle:@"忘记手势密码?" forState:UIControlStateNormal];
        [forgetpwd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [forgetpwd addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_gestureBackView addSubview:forgetpwd];
        
        _otherBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _otherBtn.frame = CGRectMake(self.view.frame.size.width-140, self.view.frame.size.height-40, 120, 15);
        _otherBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
        [_otherBtn setTitle:@"使用其他账号登录" forState:UIControlStateNormal];
        [_otherBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_otherBtn addTarget:self action:@selector(otherBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_gestureBackView addSubview:_otherBtn];
    }
    
    self.lockView = [[GestureLockView alloc] initWithFrame:CGRectMake(0, -70, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.lockView.normalGestureNodeImage = [UIImage imageNamed:@"gesture_node_normal"];
    self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_node_selected"];
    self.lockView.lineColor = [[ColorTools colorWithHexString:@"#52C470"] colorWithAlphaComponent:1.0];
    self.lockView.lineWidth = 2;
    self.lockView.delegate = self;
    if(self.view.frame.size.height == 480) {
        self.lockView.contentInsets = UIEdgeInsetsMake(self.view.frame.size.height*0.5+30, self.view.frame.size.width*0.13, 5, self.view.frame.size.width*0.13);
    }else {
        self.lockView.contentInsets = UIEdgeInsetsMake(self.view.frame.size.height*0.5+30, self.view.frame.size.width*0.12, 25, self.view.frame.size.width*0.12);
    }
    [_gestureBackView addSubview:self.lockView];
}


#pragma mark - GesturelockView
- (void)gestureLockView:(GestureLockView *)gestureLockView didBeginWithPasscode:(NSString *)passcode{
    
    self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_node_selected"];
    
    self.lockView.lineColor = KColor;
    
    _againLabel.textColor = KColor;
    
    _againLabel.text = @"";
    
    [self.lockView setNeedsDisplay];
}

- (void)gestureLockView:(GestureLockView *)gestureLockView didEndWithPasscode:(NSString *)passcode
{
    DLOG(@"%@",passcode);

    //获取当前用户手势密码
    NSString *gesPwd = [[GesDatabase getInstance]getGesturePwd:[[AppDefaultUtil sharedInstance] getDefaultAccount]];
    //手势密码解密
    NSString *gesturesPassword = [NSString decrypt3DES:gesPwd key:DESkey];
    
    DLOG(@"手势密码为:%@",gesturesPassword);
    if (![passcode isEqualToString:gesturesPassword]) {
        _count++;
        if (_count < 5) {
            
            _againLabel.text = [NSString stringWithFormat:@"密码错误还可以尝试%ld次", 5 - _count];
            
            [CommonClass shakeAnimationForView:_againLabel];
            _otherBtn.userInteractionEnabled = YES;
            
        }else {
            
            _againLabel.text = @"手势解锁已关闭";
            
            self.lockView.userInteractionEnabled = 0;
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经超过限定次数，请通过忘记手势密码重新设置！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert1.tag = 1;
            
            [alert1 show];
            
        }
        
        _againLabel.textColor = [UIColor redColor];
        self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_wrong_selected"];
        self.lockView.lineColor = KWrongLineColor;
        [self.lockView setNeedsDisplay];
        
        
    }else {
        _otherBtn.userInteractionEnabled = NO;
        [_nameLabel removeFromSuperview];
        [_lockView  removeFromSuperview];
        [_againLabel removeFromSuperview];
        
        
        //修改手势头像不用动画
        if (self.type == ModifyGesturePwd) {
            [self openLockSucceed];
            return;
        }
        
        [UIView animateWithDuration:1.0 animations:^{
            
            //头像下移居中
            _headView.center = CGPointMake(self.view.frame.size.width*0.5, self.view.frame.size.height*0.5);
            
        } completion:^(BOOL finished) {
            
            [self openLockSucceed];
            
        }];
    }
}

- (void)gestureLockView:(GestureLockView *)gestureLockView didCanceledWithPasscode:(NSString *)passcode
{
    DLOG(@"%@",passcode);
}


#pragma  mark 使用其他账号登陆
- (void)otherBtnClick
{
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
    DLOG(@"登录其他帐号");
    
    //忘记手势密码或手势密码错误
    self.lockView.userInteractionEnabled = 0;
    
//    [[GesDatabase getInstance] deleteUserInfoWithUser:[[AppDefaultUtil sharedInstance] getDefaultAccount]];// 移除该账号的手势密码
    [[AppDefaultUtil sharedInstance] setDefaultUserName:@""];// 清除用户账号
    [[AppDefaultUtil sharedInstance] setDefaultAccount:@""];// 清除用户账号
    [[AppDefaultUtil sharedInstance] setDefaultUserPassword:@""];// 清除用户密码
    [[AppDefaultUtil sharedInstance] setDefaultHeaderImageUrl:@""];// 清除用户头像
    //退出登录
    AppDelegateInstance.userInfo = nil;
    AppDelegateInstance.userInfo.isLogin = 0;
    
    // 通知全局广播 LeftMenuController 修改UI操作
    [[NSNotificationCenter defaultCenter]postNotificationName:@"update" object:nil];
    
    
    SGLoginViewController *OtherLoginVC= [[SGLoginViewController alloc] init];
    OtherLoginVC.backType = OtherLoginEnter;
    
    switch (self.type) {
        case LaunchingEnter:
        {
            //启动程序进入手势
            //OtherLoginVC.type = didFinishLaunching;
            UINavigationController *OtherLoginNav = [[UINavigationController alloc] initWithRootViewController:OtherLoginVC];
            AppDelegateInstance.window.rootViewController = OtherLoginNav;
        }
            break;
        case ModifyGesturePwd://关闭手势
        case CloseGesturePwd:
        {
            //修改手势
            //OtherLoginVC.type = Gesture;
            self.navigationController.navigationBarHidden = NO;
            [self.navigationController pushViewController:OtherLoginVC animated:YES];
        }
            break;
        case BackgroundEnter:
        {
            //退到后台进入手势
            self.navigationController.navigationBarHidden = NO;
            [self.navigationController pushViewController:OtherLoginVC animated:YES];
        }
            break;
        default:
            break;
    }
    
}

#pragma  mark - 忘记手势密码
- (void)forgetBtnClick
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"是否清空当前用户信息？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alertView.tag = 2;
    
    [alertView show];
}


#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if ((alertView.tag == 1 || alertView.tag == 2) && buttonIndex == 0) {
        
        //忘记手势密码或手势密码错误
        self.lockView.userInteractionEnabled = 0;
        
        [[GesDatabase getInstance] deleteUserInfoWithUser:[[AppDefaultUtil sharedInstance] getDefaultAccount]];// 移除该账号的手势密码
        
        //退出登录
        AppDelegateInstance.userInfo = nil;
        AppDelegateInstance.userInfo.isLogin = 0;
        
        // 通知全局广播
        [[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:nil];
        
        
        //忘记手势->重新登录->登录界面
        
        SGLoginViewController *loginVC= [[SGLoginViewController alloc] init];
     
        switch (self.type) {
            case LaunchingEnter:
            {
                //启动程序进入手势
                loginVC.backType = ChangeRootView;
                UINavigationController *loginNav = [[UINavigationController alloc] initWithRootViewController:loginVC];
                AppDelegateInstance.window.rootViewController = loginNav;
            }
                break;
            case ModifyGesturePwd: //修改手势
            case CloseGesturePwd://关闭手势
            {
                loginVC.backType = SecuritySet;
                self.navigationController.navigationBarHidden = NO;
                [self.navigationController pushViewController:loginVC animated:YES];
            }
                break;
            case BackgroundEnter:
            {
                //从后台进入手势
                loginVC.backType = EnterBackground;
                self.navigationController.navigationBarHidden = NO;
                [self.navigationController pushViewController:loginVC animated:YES];
            }
                break;
            default:
                break;
        }
    }

}


#pragma mark - 解锁成功
- (void)openLockSucceed
{
    switch (_type)
    {
        case LaunchingEnter:
        case BackgroundEnter:
        {
            [self login];
        }
            break;
        case ModifyGesturePwd:
        {
            SetGestureLockViewController *setGesturesVC = [[SetGestureLockViewController alloc]init];
            setGesturesVC.backType = 2;
            [self.navigationController pushViewController:setGesturesVC animated:NO];
        }
            break;
        case CloseGesturePwd:
        {
            //关闭手势状态
            NSString *account=[[AppDefaultUtil sharedInstance]getDefaultAccount];
            [[GesDatabase getInstance] updateGestureState:account gestureState:@"0"];
            
             [SVProgressHUD showSuccessWithStatus:@"手势密码已关闭!"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * 600000000ull)), dispatch_get_main_queue(), ^{
                
                self.navigationController.navigationBarHidden = NO;
                [self.navigationController popViewControllerAnimated:YES];
            });

        }
            break;
        default:
        {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
    }
}

    

- (void) login
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *name = [[AppDefaultUtil sharedInstance] getDefaultAccount];
    NSString *password = [[AppDefaultUtil sharedInstance] getDefaultUserPassword];
   // NSString *deviceType = [[AppDefaultUtil sharedInstance] getdeviceType];
    [parameters setObject:@"1" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:name forKey:@"name"];
    [parameters setObject:password forKey:@"pwd"];
    if(AppDelegateInstance.userId !=nil && AppDelegateInstance.channelId != nil)
    {
      [parameters setObject:AppDelegateInstance.userId forKey:@"userId"];
      [parameters setObject:AppDelegateInstance.channelId forKey:@"channelId"];
      
    }else{
    
    
        [parameters setObject:@"" forKey:@"userId"];
        [parameters setObject:@"" forKey:@"channelId"];
    
    }
    [parameters setObject:@"2" forKey:@"deviceType"];
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
       
    }
    
    [_requestClient requestGet:@"app/services" withParameters:parameters];

}


#pragma HTTPClientDelegate 网络数据回调代理
-(void) startRequest
{
    
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj
{
    
    NSDictionary *dics = obj;
    
    DLOG(@"手势登陆返回--->%@",dics);

    
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
  
        //处理登录数据
        [CommonClass loginSuccessWithDictionary:dics];
        
        // 通知全局广播 LeftMenuController 修改UI操作
        [[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:[obj objectForKey:@"username"]];
       
        [self loginSuccess];// 登录成功
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    
    }else {
        DLOG(@"返回失败  msg -> %@",[obj objectForKey:@"msg"]);
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [obj objectForKey:@"msg"]]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * 600000000ull)), dispatch_get_main_queue(), ^{
           [self otherBtnClick];
        
        });
    }
}

// 返回失败
-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error
{
    
    [self otherBtnClick];
    
//    [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"];
 
}

// 无可用的网络
-(void) networkError
{
   [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * 600000000ull)), dispatch_get_main_queue(), ^{
       [self otherBtnClick];
    });
    
}

- (void)loginSuccess
{
    if(self.type == LaunchingEnter)
    {
        TabViewController *mainVC = [TabViewController shareTableView];
        AppDelegateInstance.window.rootViewController = mainVC;
    }else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}

@end
